package com.wx.activitys.drp.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.wx.activitys.base.utils.BaseUtils;
import com.wx.activitys.base.utils.WebUtil;
import com.wx.activitys.drp.JsonResult;
import com.wx.activitys.drp.model.BPlatfrom;
import com.wx.activitys.drp.service.BClickService;
import com.wx.activitys.drp.service.DigitalSignature;
import com.wx.activitys.drp.service.PlatfromService;

@Controller
public class HomeController {
	public static final String ROOT_NAME = "drp";
	@Autowired
	private PlatfromService platfromService;
	@Autowired
	private BClickService bClickService;


	/* 拍拍贷 */
	 static final String TOKEN ="f00624a3ca6342c6b12c2355132613c2";

	/**
	 * 首页
	 */
	@RequestMapping(value = "home.html", method = RequestMethod.GET)
	public String index(Model model, HttpServletRequest request) {
		 BPlatfrom entity= new BPlatfrom();
	        entity.setState(1);
	        entity.setType(1);
	        entity.getMap().put("sort","sort");
	        List<BPlatfrom> bPlatfroms=platfromService.findByEntity(entity);
			model.addAttribute("bPlatfroms", bPlatfroms);

		return ROOT_NAME + "/home2";
	}
	
	@RequestMapping(value = "getPlat.html", method = RequestMethod.POST)
	@ResponseBody
	public Object index2(Model model, HttpServletRequest request) {
		int type=WebUtil.getInt(request, "type", 1); 
		BPlatfrom entity= new BPlatfrom();
        entity.setState(1);
        entity.setType(type);
        entity.getMap().put("sort","sort");
        List<BPlatfrom> bPlatfroms=platfromService.findByEntity(entity);
	    Map<String,Object> map = new HashMap<String, Object>();
	    map.put("bPlatfroms", bPlatfroms);
	    return map;
	}

	/**
	 * 卡卡贷接入一面 请求参数： uuid：用户唯一标识号，同一个用户用户标识相同，长度不超过40 source：渠道（固定值），卡卡贷提供source
	 * ：jiahua timestamp：时间戳 signature：数字签名
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/home/kkd.html")
	public void tokkd(HttpServletRequest request, HttpServletResponse response) {
		String uuid = DigitalSignature.getUUID();
		long timestamp = System.currentTimeMillis();
		String data = uuid + "jiahua" + timestamp;
		// 数字签名加密
		String signature = null;
		try {
			signature = DigitalSignature.signBase64(data, DigitalSignature.PRIVATE_KEY);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			response.sendRedirect("http://third.kkcredit.cn/#/wcIndex/init?uuid=" + uuid + "&source=jiahua&timestamp="+ timestamp + "&signature=" + URLEncoder.encode(signature, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 拍怕贷注册页面
	 */

	@RequestMapping(method = { RequestMethod.GET }, value = "/home/ppd.html")
	public String ppHtml(Model model, HttpServletRequest request, HttpServletResponse response) {
		//BUserInfo userInfo = UserInfo.findByOpenid("oCdHJwyeu0zfSqzwRKlLPba2_Tdo");
		GetUserInfoResponse userInfo = ((GetUserInfoResponse)request.getSession().getAttribute("userInfo"));
		model.addAttribute("userInfo", userInfo);
		return ROOT_NAME + "/ppdReg";
	}

	/**
	 * 拍拍贷(注册)
	 * API文档地址：http://cps.ppdai.com/apidoc/index?doc=channelRegLogin
	 */
	@RequestMapping(value = { "/home/ppdReg.html" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult regLogin(HttpServletRequest request, HttpSession session) {

		String ChannelId = "217";
		String SourceId = "379";
		String phone = WebUtil.getString(request, "phone", "");
		String orderId = WebUtil.getString(request, "openid", "");
		String name = WebUtil.getString(request, "name", "");
		String idNumber = WebUtil.getString(request, "idNumber", "");
		String sign = null;
		try {
			String paramMd5Str = BaseUtils.Md5("token=" + TOKEN + "&phone=" + phone);
			sign = BaseUtils.Md5("token=" + TOKEN + "&phone=" + phone + "&paramMd5=" + paramMd5Str);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		PostMethod postMethod = new PostMethod("http://cps.ppdai.com/bd/RegPostLisgting");
		postMethod.addParameter("ChannelId", ChannelId);
		postMethod.addParameter("SourceId", SourceId);
		postMethod.addParameter("token", TOKEN);
		postMethod.addParameter("sign", sign);
		postMethod.addParameter("phone", phone);//手机号
		postMethod.addParameter("userName", name);//真实姓名
		postMethod.addParameter("shenfenzh", idNumber);//身份证号
		postMethod.addParameter("applyLoanAmount", "3000");//applyLoanAmount --> 货款申请金额 整数数字 单位元 （必选）
		postMethod.addParameter("applyLoanMonth", "12");//applyLoanMonth --> 货款申请期限 整数数字 范围7-12 单位月 （必选）
		postMethod.addParameter("daikuanyt", "消费");//daikuanyt --> 贷款用途 内容为汉字，字数不超过6个 （必选）
		postMethod.addParameter("orderId", orderId);
		HttpClient httpClient = new HttpClient();
		httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		try {
			httpClient.executeMethod(postMethod);
			System.out.println(postMethod.getResponseBodyAsString());
			return JsonResult.success("1", postMethod.getResponseBodyAsString());

		} catch (IOException e) {
			e.printStackTrace();
		}
		return JsonResult.success("3", "系统错误");
	}

	/**
	 * 拍拍贷(查寻信息接口)
	 * API文档地址：http://cps.ppdai.com/apidoc/index?doc=getUserListing
	 */
	@RequestMapping(value = { "/home/getUserListing.html" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult getUserListing(HttpServletRequest request, HttpSession session) {
		String result = "";
		BufferedReader in = null;
		String phone = WebUtil.getString(request, "phone", "");
		String orderId = WebUtil.getString(request, "orderId", "");
		String sign = null;
		try {
			String paramMd5Str = BaseUtils.Md5("token=" + TOKEN + "&phone=" + phone);
			sign = BaseUtils.Md5("token=" + TOKEN + "&phone=" + phone + "&paramMd5=" + paramMd5Str);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			String urlNameString = "http://cps.ppdai.com/bd/GetUserListing?ChannelId=217&SourceId=379&token=" + TOKEN+ "&sign="+sign+"&phone=" + orderId;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setRequestProperty("Accept-Charset", "utf-8");
			connection.setRequestProperty("contentType", "utf-8");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			System.out.println(urlNameString);
			System.out.println(result);
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return JsonResult.success("1", result);
	}
	
	
	
	/**
	 * 贷款记录
	 */

	@RequestMapping(value = { "/home/loanRecord.html" }, method = RequestMethod.GET)
	public String loanRecord(HttpServletRequest request, HttpSession session) {
		
		return ROOT_NAME + "/loanRecord";
	}
	
	/**
	 * 点击统计
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = { "/home/clickCount.html" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult click(HttpServletRequest request,@RequestParam String platformId,@RequestParam String codeUrl) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
		    String openid=userInfo.getOpenid();
			bClickService.updateOrSave(openid, platformId);
		 }
			return JsonResult.success("成功", codeUrl);
	}

}
